package com.liyunc.socket.keepalive.server;


import com.liyunc.socket.keepalive.entity.Packet;
import com.liyunc.socket.keepalive.entity.Type;
import com.liyunc.socket.webclient.logger.Logger;

import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;

public class DstServer extends Thread {

    private final Packet packet = new Packet();

    @Override
    public void run() {
        try {
            ServerSocket server = new ServerSocket(8083);
            while (true) {
                Socket client = server.accept();
                synchronized (packet) {
                    new Thread(new ReceiveData(client)).start();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 客户端线程接口
     */
    static class ReceiveData implements Runnable {
        private final Socket client;

        public ReceiveData(Socket socket) {
            this.client = socket;
        }

        @Override
        public void run() {
            try {
                while (true) {
                    ObjectInput input = new ObjectInputStream(client.getInputStream());
                    Packet packet = (Packet) input.readObject();
                    if (packet.getType() == Type.HEART) {
                        Logger.info("心跳包~~~");
                    } else if (packet.getType() == Type.OTHER) {
                        Logger.info(Arrays.toString(packet.getData()));
                    } else {
                        Logger.error("Error~~~");
                    }
                    Thread.sleep(1000);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
